package com.byd.base;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import android.content.Context;
import com.byd.model.Path;
import com.byd.utils.CommonUtils;
import com.byd.utils.Lg;

public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
	private static MyUncaughtExceptionHandler HANDLER;
	private final String mPackageName;

	private MyUncaughtExceptionHandler(Context context) {
		mPackageName = context.getPackageName();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	public static void startWork(Context context) {
		if(HANDLER == null) {
			HANDLER = new MyUncaughtExceptionHandler(context);
		}
	}

	@Override
	public void uncaughtException(Thread thread, Throwable e) {
		Lg.wtf("UncaughtException: saved at " + Path.LOG + "/AppErr.log");
		Lg.printStackTrace(e);
		saveStackTrace(e);
		System.exit(0);
	}

	private void saveStackTrace(Throwable ex) {
		Writer writer = null;
		PrintWriter printWriter = null;
		FileOutputStream stream = null;
		try {
			writer = new StringWriter();
			printWriter = new PrintWriter(writer);
			ex.printStackTrace(printWriter);
			final File file = new File(Path.LOG, "AppErr.log");
			stream = new FileOutputStream(file, true);
			stream.write((getHeadInfo() + writer.toString() + "\r\n\r\n").getBytes());
		}
		catch (final Exception e) {
			Lg.printStackTrace(e);
		}
		finally {
			try {
				if(printWriter != null) {
					printWriter.close();
				}
			}
			catch (final Exception e) {
				Lg.printStackTrace(e);
			}
			try {
				if(writer != null) {
					writer.close();
				}
			}
			catch (final Exception e) {
				Lg.printStackTrace(e);
			}
			try {
				if(stream != null) {
					stream.close();
				}
			}
			catch (final Exception e) {
				Lg.printStackTrace(e);
			}
		}
	}

	private String getHeadInfo() {
		return "\r\n\r\n" + "[" + mPackageName + ": " + CommonUtils.getDayTime(System.currentTimeMillis()) + "]\r\n";
	}
}
